package com.wy.phenomenon;

/**
 * @author 美女
 * @date 2022/04/26 22:12
 **/
public class Main4 {
    static int r=0;//定义共享数据—静态属性的方式来体现
    static final int COUNT=1_0000_0000;//定义加减法次数
    //定义两个线程，分别对r进行+、-操作
    static class Add extends Thread{
        private Main4 o;

        public Add(Main4 o) {
            this.o = o;
        }

        @Override
        public void run() {
            synchronized (o) {
                for (int i = 0; i < COUNT; i++) {
                    r++;
                }
            }
        }
    }
    static class Sub extends Thread{
        private Main4 o;

        public Sub(Main4 o) {
            this.o = o;
        }
        @Override
        public void run() {
            synchronized (o) {
                for (int i = 0; i < COUNT; i++) {
                    r--;
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Main4 o=new Main4();
        Add add=new Add(o);
        add.start();
        Sub sub=new Sub(o);
        sub.start();
        add.join();
        sub.join();
        System.out.println(r);
    }
}

